Quibbox.EditMode.modules.menu = function ()
{
	var editors = {};
	
	function menuEdit()
	{
		var element = $(this);
		var id = element.attr('id');
		
		element.wrap('<div class="nicEdit-wrapper"></div>');
		
		// Activate editor
		editors[id] = new nicEditor({fullPanel : true}).panelInstance(id,{hasPanel : true});
		
		// Add buttons
		element.after('<input class="delete" type="button" value="Delete" style="float: right"/><input class="save" type="button" value="Save"/><input class="cancel" type="button" value="Cancel"/>');
		element.parent()
			.find('.save').click(articleSave).end()
			.find('.cancel').click(articleCancel).end()
			.find('.delete').click(articleDelete).end()
		;
	};
	
	function articleSave()
	{
		var element = $(this).parent().find('div').slice(-1);
		var id = element.attr('id');
		
		// Remove editor instance
		editors[id].removeInstance(id);
		
		// Unwrap element
		element.parent().after(element).remove();
		
		Quibbox.RPC.call('article_save', {id: id.substr(5), content: element.html()});
	};
	
	function articleCancel()
	{
		var element = $(this).parent().find('div').slice(-1);
		var content = element.html();
		var id = element.attr('id');
		
		// Remove editor instance
		editors[id].removeInstance(id);
		
		// Restore original DOM state
		element.html(content).parent().after(element).remove();
	};
	
	function articleDelete()
	{
		var element = $(this).parent().find('div').slice(-1);
		var content = element.html();
		var id = element.attr('id');
		
		Ext.MessageBox.confirm('Confirm', 'Are you sure you want to do that?', function (btn) {
			if (btn == "yes") {
				// Remove editor instance
				editors[id].removeInstance(id);
				
				// Delete on server
				Quibbox.RPC.call('article_delete', {id: id.substr(5)});
				
				// Remove from page entirely
				element.parent().remove();
			}
		});
	};
	
	return {
		init: function(areas)
		{
			areas.find('.block.menu').dblclick(menuEdit);
			Quibbox.EditMode.addToCatalog('general',  {
				text: 'Menu',
				module: 'menu',
				desc: 'Vertical or horizontal navigation. The most important component to help your visitors get from A to B.'
			});
		},
		
		create: function(addLink)
		{
			var areaName = addLink.parent().attr('areaName');
			
			Quibbox.RPC.call('article_create', {area: areaName}, {success: function (data) {
				addLink.before('<div id="block'+data.id+'" class="block article">'+data.content+'</div>').prev()
					.dblclick(articleEdit).show("pulsate", {times: 2}, 300);
			}});
		}
	}
}();